package no.knowit.eventorama.servlet;

import java.io.IOException;
import java.util.List;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import no.knowit.eventorama.dao.EventDAO;
import no.knowit.eventorama.dataobject.Event;
import no.knowit.eventorama.util.XMPPUtil;

import com.google.appengine.api.xmpp.JID;
import com.google.appengine.api.xmpp.Message;
import com.google.appengine.api.xmpp.XMPPService;
import com.google.appengine.api.xmpp.XMPPServiceFactory;

@SuppressWarnings("serial")
public class XMPPReceiverServlet extends HttpServlet {
	private static final Logger log = Logger
			.getLogger(XMPPReceiverServlet.class.getName());

	public void doPost(HttpServletRequest req, HttpServletResponse res)
			throws IOException {
		XMPPService xmpp = XMPPServiceFactory.getXMPPService();
		Message message = xmpp.parseMessage(req);

		JID fromJid = message.getFromJid();
		String body = message.getBody();

		log.warning("Message Received. jid=" + fromJid + ", body=" + body);

		if (body.trim().toLowerCase().contains("events")) {
			sendEventList(fromJid);
		} else {
			XMPPUtil.sendMessage(fromJid, "Unrecognized command, sorry..");
		}

	}

	public void sendEventList(JID receiverJID) {

		StringBuffer sb = new StringBuffer();

		sb.append("Hi there!\n");
		sb.append("The following events have been registered in the system:\n");

		List<Event> events = (new EventDAO()).loadAll();

		for (Event event : events) {
			sb.append(" * " + event.getTitle() + "\n");
		}
		sb.append("----OK Computer");
		XMPPUtil.sendMessage(receiverJID, (sb.toString()));

	}

}